package com.jvtd.nettyim.im.util;

import com.jvtd.nettyim.im.attribute.Attributes;
import com.jvtd.nettyim.im.session.Session;
import io.netty.channel.Channel;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Created by neal.zhang
 * @date 2020/5/30 - 14:58
 */
public class SessionUtil {

    private static final ConcurrentHashMap<String, Channel> userIdChannelMap = new ConcurrentHashMap<>();

    public static void bindSession(Session session, Channel channel) {
        userIdChannelMap.put(session.getUserId(), channel);
        channel.attr(Attributes.SESSION).set(session);
    }

    public static void unBindSession(Channel channel) {
        if (hasLogin(channel)) {
            userIdChannelMap.remove(getSession(channel).getUserId());
            channel.attr(Attributes.SESSION).set(null);
        }
    }

    /**
     * 判断当前channel是否保存session
     *
     * @param channel
     * @return
     */
    public static boolean hasLogin(Channel channel) {
        return channel.hasAttr(Attributes.SESSION);
    }

    public static Session getSession(Channel channel) {
        Session session = channel.attr(Attributes.SESSION).get();
        return session;
    }

    public static Channel getChannel(String userId) {
        return userIdChannelMap.get(userId);
    }
}
